package com.fm.demo

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.SpannableString
import android.view.View
import android.view.WindowManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.binioter.guideview.GuideBuilder
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.fm.common.base.BaseBPActivity
import com.fm.common.base.BasePresenter
import com.fm.demo.activity.*
import com.fm.demo.activity.dualScreen.DualScreenActivity
import com.fm.demo.activity.dualScreen.TestDisplay
import com.fm.demo.component.MainActivityComponent
import com.fm.demo.databinding.ActivityMainBinding
import com.fm.demo.jet_pack.JetPackActivity
import com.fm.demo.joke.JokeMainActivity
import com.fm.demo.jpush.JPushActivity
import com.fm.demo.service.ScreenShotFloatWindowsService
import com.fm.demo.utils.CommonUtils
import com.fm.demo.utils.DialogUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
import kotlin.math.min


/**
 * @CreateData:     2019/11/1 9:33
 * @E-Mail:         709674174@qq.com
 * @Author:         lyy
 * @Description:    测试模块入口
 */
class MainActivity : BaseBPActivity<ActivityMainBinding, BasePresenter<*>>(), View.OnClickListener,
    BaseBPActivity.OnNavigationOnClickListener {
    private var mDisPlay: TestDisplay? = null

    override fun initView(savedInstanceState: Bundle?) {
        initToolbar(binding.rootToolbar,"测试入口", false)
        setLeftClickListener(this)
        binding.mainBtnDialog.setOnClickListener(this)
        binding.mainBtnJetPack.setOnClickListener(this)
        binding.mainBtnScreenAddGallery.setOnClickListener(this)
        binding.mainBtnJpush.setOnClickListener(this)
        binding.mainBtnRoot.setOnClickListener(this)
        binding.mainBtnAppSystemSet.setOnClickListener(this)
        binding.mainBtnGetContacts.setOnClickListener(this)
        binding.mainBtnAppRunSelf.setOnClickListener(this)
        binding.mainBtnJoke.setOnClickListener(this)
        binding.mainBtnDualScreen.setOnClickListener(this)
        binding.mainBtnJsAndroid.setOnClickListener(this)
        binding.mainBtnSwitchZ.setOnClickListener(this)
        binding.mainBtnCupUsed.setOnClickListener(this)
        binding.mainBtnLoadingDialog.setOnClickListener(this)
        binding.mainBtnDeviceInfo.setOnClickListener(this)
        /*runOnUI {
            delay(1000)
            setGuideView()
        }*/
    }

    private fun setGuideView() {
        val guide = GuideBuilder().setAlpha(155)
            .setAutoDismiss(false)
            .setHighTargetPadding(2)
            .setOutsideTouchable(false)
            .setOverlayTarget(false)
            .setTargetView(binding.mainBtnJoke)
            .addComponent(MainActivityComponent())
            .setHighTargetClickListener {
                ToastUtils.showShort("高量区域点击")
            }
            .setOnVisibilityChangedListener(object : GuideBuilder.OnVisibilityChangedListener {
                override fun onShown() {
                }

                override fun onDismiss() {
                }
            }).createGuide()
        guide.show(this)
    }

    override fun onPostResume() {
        super.onPostResume()
        initDisplay()
    }

    override fun onStop() {
        super.onStop()
        mDisPlay?.dismiss()
    }

    /**
     * 初始化第二屏
     */
    private fun initDisplay() {
        val displayManager: DisplayManager =
            getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
        val displays = displayManager.displays
        LogUtils.e("display size : ${displays.size}")
        if (displays.size >= 2) {
            mDisPlay = TestDisplay(mContext, displays[1])
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mDisPlay?.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
            }
            mDisPlay?.show()
            mDisPlay?.setTitle("MainActivity")
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.main_btn_dialog -> {
                startActivity(Intent(mContext,CameraActivity::class.java))

//                DialogUtils.showLoadingDialog()
            }
            R.id.main_btn_jet_pack -> {
                startActivity(Intent(this, JetPackActivity::class.java))
            }
            R.id.main_btn_screen_add_gallery -> {
                val floatWindowsServiceIsRun = CommonUtils.checkServiceIsRun(
                    this,
                    ScreenShotFloatWindowsService::class.java.name
                )
                LogUtils.e("float windows service is run : $floatWindowsServiceIsRun")
                if (floatWindowsServiceIsRun) {
                    stopService(Intent(this, ScreenShotFloatWindowsService::class.java))
                    return
                }
                PermissionUtils.permission(PermissionConstants.STORAGE)
                    .callback(object : PermissionUtils.SimpleCallback {
                        override fun onGranted() {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                startActivityForResult(
                                    (getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager).createScreenCaptureIntent(),
                                    10086
                                )
                            } else {
                                ToastUtils.showShort("版本不支持")
                            }
                        }

                        override fun onDenied() {
                            PermissionUtils.launchAppDetailsSettings()
                            ToastUtils.showShort("请开启权限")
                        }
                    }).request()
            }
            R.id.main_btn_jpush -> {
                startActivity(Intent(mContext, JPushActivity::class.java))
            }
            R.id.main_btn_root -> {
                startActivity(Intent(mContext, RootActivity::class.java))
            }
            R.id.main_btn_app_system_set -> {
                MaterialDialog(mContext).show {
                    val itemTitleList = arrayOf(
                        "系统的辅助功能界面",
                        "应用程序信息界面",
                        "开发人员选项界面",
                        "应用程序界面",
                        "系统的蓝牙设置界面",
                        "移动网络设置界面",
                        "快速启动设置界面",
                        "安全设置界面",
                        "设置界面",
                        "启动及关联启动"
                    )
                    listItems(items = itemTitleList.toList()) { _, index, text ->
                        if (index == 9) {
                            val modelName =
                                Build.MANUFACTURER.toLowerCase(Locale.getDefault()) // 手机型号
                            val intent = Intent().addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            var componentName: ComponentName? = null
                            LogUtils.e("phone : $modelName")
                            when (modelName) {
                                "vivo" -> {
                                    componentName = ComponentName(
                                        "com.vivo.permissionmanager",
                                        "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
                                    )
                                }
                                "huawei" -> {
                                    componentName = ComponentName(
                                        "com.huawei.systemmanager",
                                        "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
                                    )
                                }
                                else -> {
                                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                                    intent.data =
                                        Uri.fromParts("package", context.packageName, null)
                                }
                            }
                            intent.component = componentName
                            startActivity(intent)
                        }
                        val action = when (index) {
                            0 -> Settings.ACTION_ACCESSIBILITY_SETTINGS
                            1 -> Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            2 -> Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS
                            3 -> Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS
                            4 -> Settings.ACTION_BLUETOOTH_SETTINGS
                            5 -> Settings.ACTION_DATA_ROAMING_SETTINGS
                            6 -> Settings.ACTION_QUICK_LAUNCH_SETTINGS
                            7 -> Settings.ACTION_SECURITY_SETTINGS
                            8 -> Settings.ACTION_SETTINGS
                            else -> ""
                        }
                        if (action.isNotEmpty()) {
                            val intent = Intent(action).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            if (index == 1) {
                                intent.data = Uri.fromParts("package", packageName, null)
                            }

                            startActivity(intent)
                        }
                        ToastUtils.showShort(text)
                        dismiss()
                    }
                    negativeButton(text = "关闭")
                }
            }
            R.id.main_btn_get_contacts -> {
                PermissionUtils.permission(PermissionConstants.CONTACTS)
                    .callback(object : PermissionUtils.SimpleCallback {
                        override fun onGranted() {
                            GlobalScope.launch {
                                val contacts = CommonUtils.getAllContacts(mContext)
                                LogUtils.e(contacts)
                            }
                        }

                        override fun onDenied() {
                            ToastUtils.showShort("拒绝，失败")
                        }
                    }).request()
            }
            R.id.main_btn_app_run_self -> {
                LogUtils.e(JPushActivity::class.java.name)
                GlobalScope.launch {
                    //                    val result = CommonUtils.hasStartSelf(mContext, packageName)
//                    ToastUtils.showShort(result.toString())
                }
            }
            R.id.main_btn_joke -> {
                startActivity(Intent(mContext, JokeMainActivity::class.java))
            }
            R.id.main_btn_dual_screen -> {
                startActivity(Intent(mContext, DualScreenActivity::class.java))
            }
            R.id.main_btn_js_android -> {
                startActivity(Intent(mContext, WebActivity::class.java))
            }
            R.id.main_btn_switch_z -> {
                startActivity(Intent(mContext, SwitchZActivity::class.java))
            }
            R.id.main_btn_cup_used -> {
                val info = CommonUtils.getAppMemory()
                ToastUtils.showShort("cup$info")
                LogUtils.i("cup info : $info")
            }
            R.id.main_btn_loading_dialog -> {
                startActivity(Intent(mContext, LoadingActivity::class.java))
            }
            R.id.main_btn_device_info -> {
                val deviceInfo = StringBuilder()
                val screenWidth = ScreenUtils.getScreenWidth()
                val screenHeight = ScreenUtils.getScreenHeight()
                val dpi = ScreenUtils.getScreenDensityDpi()
                deviceInfo.append("屏幕宽高： $screenWidth, $screenHeight")
                    .append("\n")
                    .append("dpi : $dpi, 最小宽度： ${min(screenWidth, screenHeight)}")
                    .append("\n")
                    .append("计算出来的 smallestWidth: ${screenWidth / (dpi / 160.0)} dp")
                    .append("\n")
                    .append("实际使用的 smallestWidth: ${resources.getString(R.string.base_dp)}")

                DialogUtils.showPromptDialog(SpannableString(deviceInfo), null, title = "设备信息")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == 10086) {
            data?.let {
                startService(
                    Intent(applicationContext, ScreenShotFloatWindowsService::class.java)
                        .putExtra("data", data)
                )
                moveTaskToBack(true)
            }
        }
    }

    override fun onNavigationClick() {
        moveTaskToBack(true)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    override fun onResume() {
        super.onResume()
        intent?.let {
            val className = intent.getStringExtra("className")
            className?.let {
                intent.setClassName(mContext, className)
                startActivity(intent)
                intent.removeExtra("className")
            }
        }
    }
}
